<template>
  <div id="main">

    <h2>系统用户管理</h2>

    <el-button type="primary" style="margin-left:20px" @click="handleOpen('添加管理员用户',1)">添加用户</el-button>

    <div id="search-card">
      <div id="search-content">
        <el-form v-model="search" :inline="true">

          <el-form-item label="昵称">
            <el-input v-model="search.username" />
          </el-form-item>

          <el-form-item label="所属品牌">
            <el-select v-model="search.orgId" placeholder="请选择">
              <el-option
                v-for="o in org"
                :key="o.orgId"
                :value="o.orgId"
                :label="o.orgName"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="用户角色">
            <el-select v-model="search.userGroup" placeholder="请选择">
              <el-option key="1" label="IT部" value="1" />
              <!-- <el-option key="2" label="代理人" value="2" /> -->
              <el-option key="3" label="品牌管理员" value="3" />
              <el-option key="4" label="机构管理员" value="4" />
              <el-option key="5" label="财务部" value="5" />
              <el-option key="6" label="人事部" value="6" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" style="margin-left:10px" @click="conditionQuery">查找</el-button>
            <el-button icon="el-icon-refresh" circle @click="fetchData()" />
          </el-form-item>

          <!-- <el-form-item label="">
            <el-input v-model="mohu" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" style="margin-left:10px" @click="mohuQuery">查找</el-button>
            <el-button icon="el-icon-refresh" circle @click="fetchData()" />
          </el-form-item> -->
        </el-form>
      </div>

    </div>

    <div id="table-area">
      <el-table
        v-loading="listLoading"
        :data="list.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >

        <el-table-column
          label="序号"
          type="index"
          width="80"
          align="center"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pagesize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="username"
          label="昵称"
        />

        <el-table-column
          align="center"
          prop="userGroup"
          label="用户角色"
        >
          <template slot-scope="Scope">
            <span v-if="Scope.row.userGroup==1">IT部</span>
            <span v-if="Scope.row.userGroup==2">代理人</span>
            <span v-if="Scope.row.userGroup==3">品牌管理员</span>
            <span v-if="Scope.row.userGroup==4">机构管理员</span>
            <span v-if="Scope.row.userGroup==5">财务部</span>
            <span v-if="Scope.row.userGroup==6">人事部</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="Scope">
            <!-- <el-button v-if="Scope.row.userGroup==2" type="primary" icon="el-icon-edit" @click="resetPwd(Scope.row.userId)">重置密码</el-button> -->
            <el-button type="primary" icon="el-icon-edit" @click="handleOpen('修改管理员用户',2,Scope.row.userId)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(Scope.row.userId,Scope.row.username)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div id="pages">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[5,10]"
          :page-size="pagesize"
          layout="total, sizes,prev, pager, next"
          :total="list.length"
          prev-text="上一页"
          next-text="下一页"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog title="" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-form ref="consoleUser" :model="consoleUser" label-position="top" :rules="rules">

        <el-form-item prop="userGroup" label="用户角色" :label-width="formLabelWidth">
          <el-select v-model="consoleUser.userGroup" placeholder="请选择">
            <el-option key="1" label="系统管理员" value="1" />
            <el-option key="3" label="品牌管理员" value="3" />
            <el-option key="4" label="机构管理员" value="4" />
            <el-option key="5" label="财务" value="5" />
            <el-option key="6" label="人事" value="6" />
          </el-select>
        </el-form-item>

        <div
          v-if="consoleUser.userGroup === '1'"
        >
          <el-form-item prop="username" label="昵称" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.username"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.password" autocomplete="off" type="password" />
          </el-form-item>

          <el-form-item prop="realname" label="账号所属人" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.realname"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="userPhone" label="手机号" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.userPhone" maxlength="11" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
          </el-form-item>
        </div>

        <div
          v-if="consoleUser.userGroup === '3'"
        >
          <el-form-item prop="username" label="昵称" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.username"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.password" autocomplete="off" type="password" />
          </el-form-item>

          <el-form-item label="所属机构" :label-width="formLabelWidth">
            <el-select v-model="consoleUser.orgId" placeholder="仅机构管理员选择">
              <el-option key="-1" label="无" value="-1" />
              <el-option
                v-for="o in org"
                :key="o.orgId"
                :value="o.orgId"
                :label="o.orgName"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="realname" label="账号所属人" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.realname"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="userPhone" label="手机号" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.userPhone" maxlength="11" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
          </el-form-item>
        </div>

        <div
          v-if="consoleUser.userGroup === '4'"
        >
          <el-form-item prop="username" label="昵称" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.username"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.password" autocomplete="off" type="password" />
          </el-form-item>

          <el-form-item prop="realname" label="账号所属人" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.realname"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="userPhone" label="手机号" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.userPhone" maxlength="11" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
          </el-form-item>
        </div>
        <div
          v-if="consoleUser.userGroup === '5'"
        >
          <el-form-item prop="username" label="昵称" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.username"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.password" autocomplete="off" type="password" />
          </el-form-item>

          <el-form-item prop="realname" label="账号所属人" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.realname"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="userPhone" label="手机号" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.userPhone" maxlength="11" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
          </el-form-item>
        </div>

        <div
          v-if="consoleUser.userGroup === '6'"
        >
          <el-form-item prop="username" label="昵称" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.username"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="password" label="密码" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.password" autocomplete="off" type="password" />
          </el-form-item>

          <el-form-item prop="realname" label="账号所属人" :label-width="formLabelWidth">
            <el-input
              v-model="consoleUser.realname"
              autocomplete="off"
              maxlength="20"
              show-word-limit
            />
          </el-form-item>

          <el-form-item prop="userPhone" label="手机号" :label-width="formLabelWidth">
            <el-input v-model="consoleUser.userPhone" maxlength="11" autocomplete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">取 消</el-button>
        <el-button v-if="editType==2" type="primary" @click="handleUpdate('consoleUser')">修 改</el-button>
        <el-button v-if="editType==1" type="primary" @click="handleAddUser('consoleUser')">添 加</el-button>
      </div>
    </el-dialog>

  </div>

</template>
<script>
import { getAllConsoleUserExceptRecommend, getConsoleUserById, addUser1, addUser2, addUser3, addUser4, deleteUser, updateUser1, updateUser2, updateUser3, conditionSearch, mohuSearch, judgment, judgement, resetPwd } from '@/api/consoleUser'
import { getAllOrg } from '@/api/org'
export default {

  data() {
    var checkphone = (rule, value, callback) => {
    // let phoneReg = /(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/;
      if (value == null) {
        callback(new Error('请输入手机号'))
      } else if (!this.isCellPhone(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }
    var checkBankName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入开户行'))
      } else if (!this.isChinese(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入中文'))
      } else {
        callback()
      }
    }
    var checkAccountName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入户名'))
      } else if (!this.isChinese(value)) { // 引入methods中封装的检查手机格式的方法
        callback(new Error('请输入中文'))
      } else {
        callback()
      }
    }
    return {
      currentPage: 1, // 默认显示页面为1
      pagesize: 5, //    每页的数据条数
      url: process.env.VUE_APP_BASE_API + 'file/',
      list: [],
      listLoading: false,
      dialogFormVisible: false,
      pwdFormVisible: false,
      org: {},
      editType: 1, // 1 添加 2 修改
      search: {},
      mohu: '',
      consoleUser: {},
      formLabelWidth: '200px',
      fileList: [],
      fileUrl: '',
      rules: {
        username: [{ required: true, validator: this.checkName, trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }, { min: 8, max: 12, message: '密码建议在8~12位', trigger: 'blur' }],
        userGroup: [{ required: true, message: '请选择用户角色' }],
        realname: [{ required: true, message: '请输入账号所属人', trigger: 'blur' }],
        userPhone: [{ required: true, validator: checkphone, trigger: 'blur' }],
        email: [{ required: true, validator: this.checkEmail, trigger: 'blur' }],
        bankName: [{ required: true, validator: checkBankName, trigger: 'blur' }],
        idcard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
        accountName: [{ required: true, validator: checkAccountName, trigger: 'blur' }],
        accountId: [{ required: true, message: '请输入账号', trigger: 'blur' }]

      }
    }
  },
  created() {
    this.fetchData()
    this.getAllOrg()
  },
  methods: {
    // 每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size
    },
    // 点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage
    },
    handleClick(row) {
      console.log(row)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.fileUrl = ''
      for (var i = 0; i < fileList.length; i++) {
        this.fileUrl = this.fileUrl + fileList[i].response.obj
        console.log(1)
      }
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleAvatarSuccess(res, file) {
      // this.fileUrl.push({
      //   name: file.name,
      //   url: res.obj
      // })
      this.fileUrl = this.fileUrl + res.obj
      // console.log(this.consoleUser.file)
      // console.log(this.fileUrl)
    },
    fetchData() {
      this.search = {}
      this.listLoading = true
      getAllConsoleUserExceptRecommend().then((data) => {
        this.list = data.obj
        this.listLoading = false
      })
    },
    handleDelete(id, username) {
      this.$confirm('确认删除该用户？昵称为' + username).then(() => deleteUser(id).then((data) => {
        this.$notify({
          title: '操作成功',
          type: 'success'
        })
        const totalPage = Math.ceil((this.list.length - 1) / this.pagesize)
        const page = this.currentPage > totalPage ? totalPage : this.currentPage
        this.currentPage = this.currentPage < 1 ? 1 : page
        this.fetchData()
      }))
    },
    handleAddUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.consoleUser.userGroup === '1' || this.consoleUser.userGroup === '5' || this.consoleUser.userGroup === '6') {
            console.log('系统管理员')
            addUser1(this.consoleUser).then((resp) => {
              this.$notify({
                title: '操作成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.consoleUser = {}
            this.dialogFormVisible = false
          }
          if (this.consoleUser.userGroup === '2') {
            this.consoleUser.file = this.fileUrl
            addUser2(this.consoleUser).then((resp) => {
              this.$notify({
                title: '操作成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.consoleUser = {}
            this.dialogFormVisible = false
          }
          if (this.consoleUser.userGroup === '3') {
            console.log('品牌管理员')
            addUser3(this.consoleUser).then((resp) => {
              this.$notify({
                title: '操作成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.consoleUser = {}
            this.dialogFormVisible = false
          }
          if (this.consoleUser.userGroup === '4') {
            console.log('机构管理员')
            addUser4(this.consoleUser).then((resp) => {
              this.$notify({
                title: '操作成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.consoleUser = {}
            this.dialogFormVisible = false
          }
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    handleOpen(title, type, id) {
      this.consoleUser = {}
      this.dialogFormVisible = true
      this.title = title
      this.editType = type
      if (type === 2) {
        getConsoleUserById(id).then((resp) => {
          this.consoleUser = resp.obj
          this.consoleUser.userGroup = String(this.consoleUser.userGroup)
          this.consoleUser.sex = String(this.consoleUser.sex)
          if (this.consoleUser.orgId === -1) {
            this.consoleUser.orgId = '-1'
          }
        })
      }
    },
    handleClose() {
      this.dialogFormVisible = false
      this.consoleUser = {}
    },
    handleUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.consoleUser.userGroup === '1' || this.consoleUser.userGroup === '5' || this.consoleUser.userGroup === '6') {
            updateUser1(this.consoleUser).then((resp) => {
              this.$notify({
                title: '修改成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.dialogFormVisible = false
          }
          if (this.consoleUser.userGroup === '2') {
            this.consoleUser.file = this.fileUrl
            updateUser2(this.consoleUser).then((resp) => {
              this.$notify({
                title: '修改成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.dialogFormVisible = false
          }
          if (this.consoleUser.userGroup === '3') {
            updateUser3(this.consoleUser).then((resp) => {
              this.$notify({
                title: '修改成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.dialogFormVisible = false
          }
          if (this.consoleUser.userGroup === '4') {
            updateUser1(this.consoleUser).then((resp) => {
              this.$notify({
                title: '修改成功',
                type: 'success'
              })
              this.fetchData()
            })
            this.dialogFormVisible = false
          }
          return true
        } else {
          this.$notify({
            title: '请正确填写',
            type: 'error'
          })
          return false
        }
      })
    },
    resetPwd(userId) {
      resetPwd(userId).then((data) => {
        this.$notify({
          title: '重置成功',
          type: 'success'
        })
        this.fetchData()
      })
    },
    getAllOrg() {
      getAllOrg().then((resp) => {
        this.org = resp.obj
      })
    },
    conditionQuery() {
      conditionSearch(this.search).then((data) => {
        this.list = data.obj

        this.currentPage = 1
      })
    },
    mohuQuery() {
      mohuSearch(this.mohu).then((data) => {
        this.list = data.obj
        this.currentPage = 1
      })
    },
    isCellPhone(val) {
      if (!/^1[3456789]\d{9}$/.test(val)) {
        return false
      } else {
        return true
      }
    },
    isChinese(val) {
      if (/[^\u4E00-\u9FA5]/.test(val)) {
        return false
      } else {
        return true
      }
    },
    // 特殊字符过滤
    checkSpecificKey(str) {
      var specialKey = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'"
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) !== -1) {
          return false
        }
      }
      return true
    },

    // 验证字符串
    validateFontSize(rule, value, callback) {
      if (value.length < 30) {
        callback()
      } else {
        callback(new Error('字符串长度在1-30之间'))
      }
    },

    // 验证字符串
    validateCharacter(rule, value, callback) {
      if (this.checkSpecificKey(value)) {
        callback()
      } else {
        callback(new Error('请不要输入特殊字符'))
      }
    },
    checkRtelePhone(rule, value, callback) {
      if (!value) {
        return callback(new Error('联系电话不能为空'))
      } else {
        const reg = /^(0\d{2,3}-?)?[0-9]{7,8}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的联系电话'))
        }
      }
    },
    checkEmail(rule, value, callback) {
      if (!value) {
        return callback(new Error('电子邮箱不能为空'))
      } else {
        const reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入有效的电子邮箱！'))
        }
      }
    },
    onInputBlur() {

    },
    checkName(rule, value, callback) {
      if (this.editType === 1) {
        if (!value) {
          return callback(new Error('昵称不能为空'))
        } else {
          judgment(this.consoleUser.username).then((resp) => {
            if (resp.msg === '该昵称已存在！') {
              return callback(new Error('该昵称已存在！'))
            }
            if (resp.msg === '该昵称可用！') {
              callback()
            }
          })
        }
      } else if (this.editType === 2) {
        if (!value) {
          return callback(new Error('昵称不能为空'))
        } else {
          judgement(this.consoleUser.username, this.consoleUser.userId).then((resp) => {
            if (resp.msg === '该昵称已存在！') {
              return callback(new Error('该昵称已存在！'))
            }
            if (resp.msg === '该昵称可用！') {
              callback()
            }
          })
        }
      } else {
        callback()
      }
    },

    updateCheckName(rule, value, callback) {
      if (this.editType === 2) {
        if (!value) {
          return callback(new Error('昵称不能为空'))
        } else {
          judgment(this.consoleUser.username).then((resp) => {
            if (resp.msg === '该昵称已存在！') {
              return callback(new Error('该昵称已存在！'))
            }
            if (resp.msg === '该昵称可用！') {
              callback()
            }
          })
        }
      } else {
        callback()
      }
    }
  }

}
</script>

<style scoped>
#main{
  margin-left: 5px;
  margin-right: 5px;
}
#table-area{
  margin-left: 10px;
  margin-right: 10px;
}
#search-card {
  line-height: 0px;
  text-align: right;
  width: 100%;
  height: 70px;
  overflow-x: hidden;
}
</style>
